package ink.ykb.rpn;

/**
 * 栈
 */
public class Stack<E> {

  private int maxSize;

  private LinkList<E> stackArray;

  private int top;

  public Stack(int maxSize) {
    this.maxSize = maxSize;
    this.stackArray = new LinkList<E>();
    this.top = -1;
  }

  public Stack() {
    this.stackArray = new LinkList<E>();
    this.top = -1;
    this.maxSize = -1;
  }

  /**
   * 入栈
   * 
   * @param e
   */
  public boolean push(E e) {
    if(isFull()) {
      return false;
    }
    
    top++;
    stackArray.insertFirst(e);
    
    return true;
  }

  /**
   * 出栈
   * 
   * @return
   */
  public E pop() {
    if(isEmpty()) {
      return null;
    }
    
    top--;
    Link<E> deleteFirst = stackArray.deleteFirst();
    if (deleteFirst != null) {
      return deleteFirst.getData();
    }
    return null;
  }
  
  

  /**
   * 查看栈顶
   * 
   * @return
   */
  public E peek() {
    Link<E> first = stackArray.getFirst();
    if (first != null) {
      return first.getData();
    }
    return null;
  }
  
  public E peekN(int n) {
    Link<E> first = stackArray.getFirst();
    int p = 0;
    while (first != null && (p < n)) {
      first = first.getNext();
      p++;
    }
    if (first != null) {
      return first.getData();
    }
    return null;
  }

  public boolean isEmpty() {
    return top == -1;
  }

  public boolean isFull() {
    return top == maxSize - 1;
  }


  public void displayStack() {
    System.out.println("Stack (bottom --> top)：");
    Link<E> last = stackArray.getLast();
    while (last != null) {
      System.out.println(last);
      last = last.getPrevious();
    }
    System.out.println("");
  }

  public int size() {
    return top + 1;
  }
  
 

}
